package cn.dazhou.andserverdemo

import android.util.Log
import com.yanzhenjie.andserver.AndServer
import com.yanzhenjie.andserver.Server
import java.lang.Exception
import java.util.concurrent.TimeUnit

object AndServerEngine {

    private var mAndServer: Server? = null

    fun startup() {
        if (mAndServer?.isRunning == true) {
            Log.i("ABCD", "AndServer已经启动")
            return
        }

        AndServer
            .webServer(App.sContext)
            .port(8899)
            .timeout(10, TimeUnit.SECONDS)
            .listener(object : Server.ServerListener {
                override fun onStarted() {
                    Log.i("ABCD", "AndServer启动成功")
                }

                override fun onStopped() {
                    Log.i("ABCD", "AndServer关闭成功")
                }

                override fun onException(e: Exception?) {
                    Log.i("ABCD", "AndServer出现异常", e)
                }

            })
            .build()
            .apply {
                mAndServer = this
                startup()
            }
    }

    fun shutdown() {
        val server = mAndServer
        if (server?.isRunning == true) {
            server.shutdown()
            mAndServer = null
        } else {
            Log.i("ABCD", "AndServer没有启动")
        }
    }

}